<template>

    <div class="detail-images" v-show="materialList && materialList.length > 0" :class="{ active: materialSelect.length }">
        <div class="detail-images-title" :fixed="fixedHead ? 'fixed' : ''">
            <p>
                <svg-icon name="notify2" />
                <em>We provide these free model images at your disposal in case our mannequin images can't meet your
                    needs.</em>
            </p>
            <fieldset>
                <span :class="{ active: materialSelect.length >= materialList.length }" @click="setMaterialSelect()">
                    <svg-icon name="checkbox-active" />
                    <em v-if="materialSelect.length >= materialList.length">Deselect all</em>
                    <em v-else>Select all</em>
                </span>
                <button type="primary" @click="downloadMaterial()"
                        :disabled="materialSelect.length == 0">Download</button>
            </fieldset>
        </div>

        <ul>
            <li v-for="item in materialList" :key="item.url" :class="{ active: materialSelect.indexOf(item.url) >= 0 }">
                <figure @click="setMaterialSelect(item)">
                    <img v-lazy="$getImageUrl(item.url)" :style="$fiexImage(item.width, item.height, 1)">
                </figure>
                <span @click="priviewMaterial(item)"><svg-icon name="user-files-preview" /></span>
                <i>
                    <svg-icon name="checkbox-active" />
                </i>
            </li>
        </ul>

        <!-- 下载进度弹窗 -->
        <UxDialog :visible="!!downloading" class="detail-downloading" :can-close="false">
            <el-progress type="circle" color="#ea4c89" :percentage="downloading" :width="96"></el-progress>
            <p>Downloading</p>
        </UxDialog>

        <!-- 大图预览 -->
        <UxImagePreview v-model="preview" />
    </div>

</template>
<script>
import JSZip from "jszip";
import FileSaver from "file-saver";
export default {
    props: {
        detail: { type: Object, default: () => ({}) },
    },
    data () {
        return {
            downloading: 0,
            preview: null,
            preview: null, // 大图预览
            top: 0,
            fixedHead: false,
            materialSelect: [],
        };
    },
    computed: {

        materialList () {
            try {
                return JSON.parse(this.detail.mockup || '[]');
            } catch (error) {
                return []
            }
        }

    },


    methods: {
        // 选中或取消选中
        setMaterialSelect (item) {

            if (item) {
                const index = this.materialSelect.indexOf(item.url);
                if (index >= 0) {
                    this.materialSelect.splice(index, 1)
                } else {
                    this.materialSelect.push(item.url);
                }
            } else {
                if (this.materialSelect.length >= this.materialList.length) {
                    this.materialSelect = []
                } else {
                    this.materialSelect = this.materialList.map(item => item.url);
                }
            }

            this.top = this.$el.offsetTop
            this.checkHeaderActive()
        },

        // 预览
        priviewMaterial (item) {
            const urls = (this.materialList || []).map(i => i.url);
            const index = urls.indexOf(item.url);
            this.preview = {
                index: index,
                images: urls.map(url => this.$getImageUrl(url, 'preview')),
            };
        },

        downloadMaterial () {
            // 制作压缩包
            const percent = {
                count: 0,
                total: 0,
                timer: null,
                value: 0,
            }

            const setPercent = (init) => {

                if (!init) {
                    percent.count += 1;
                    percent.value = Math.max(1, Math.min(100, parseInt(100 * (percent.count / percent.total))));
                    this.downloading = percent.value
                } else {
                    //
                }

                let value = Math.max(1, Math.min(99, parseInt(100 * ((percent.count + 1) / percent.total))))

                if (percent.value >= value) {
                    percent.timer && clearTimeout(percent.timer);
                } else {
                    const time = parseInt(Math.random() * 1000)
                    percent.value += 1;
                    percent.timer && clearTimeout(percent.timer);
                    percent.timer = setTimeout(e => setPercent(true), time)
                    this.downloading = percent.value;
                }
            }

            const zip = new JSZip();
            const loadImage = (zip, url, index) => {
                return new Promise((resolve, reject) => {

                    const xhr = new XMLHttpRequest();
                    const type = (url.match(/.(png|jpe?g|gif)/gi) || [])[0] || ''
                    const name = 'Model_images' + (index + 1) + type;

                    xhr.open("get", this.$getImageUrl(url, 'original'), true);
                    xhr.responseType = "blob";
                    xhr.onload = () => {
                        if (xhr.status == 200) {
                            zip.file(name, xhr.response);
                            setPercent();
                            resolve(url);
                        }
                    };
                    xhr.onerror = () => {
                        reject();
                    };
                    xhr.send();
                });
            }

            const promises = this.materialSelect.map((url, index) => loadImage(zip, url, index));

            percent.total += this.materialSelect.length;
            percent.value = 1;
            this.downloading = percent.value;
            setPercent(true);


            Promise.all(promises).then(res => {
                return zip.generateAsync({ type: "blob" })
            }).then(content => {
                FileSaver(content, "Model_Images.zip");
                this.$uxMessage.success('Successfully downloaded.')
                this.downloading = 0;
            }).catch((error) => {
                this.$uxMessage.error('Download failed. Please try again.')
                this.downloading = 0;
            });
        },

        checkHeaderActive () {
            const scrollY = document.documentElement.scrollTop || document.body.scrollTop
            this.fixedHead = scrollY >= (this.top + 6);
        },

    },

    mounted () {
        setTimeout(() => {
            this.top = this.$el.offsetTop
            this.checkHeaderActive()
        }, 10);
        window.addEventListener('scroll', this.checkHeaderActive)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.checkHeaderActive)
    }
};
</script>
<style lang="scss" scoped>
.detail-images {
    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #e6e6e6;
    padding: 26px;

    .detail-images-title {
        background: #fff;
        width: 100%;
        display: flex;
        align-items: center;
        font-weight: normal;
        box-sizing: border-box;
        position: relative;

        &>p {
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #292929;
            line-height: 16px;
            display: flex;
            align-items: center;

            &>svg {
                width: 14px;
                height: 14px;
                color: #acacac;
                margin-right: 4px;
            }
        }

        &>fieldset {
            display: flex;
            align-items: center;
            position: absolute;
            right: 0;
            top: 0;
            margin-top: -10px;
            opacity: 0;
            pointer-events: none;

            &>span {
                width: 74px;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #000000;
                line-height: 16px;
                padding-left: 22px;
                cursor: pointer;
                position: relative;

                &::before {
                    content: '';
                    position: absolute;
                    left: 0;
                    top: 50%;
                    box-sizing: border-box;
                    transform: translateY(-50%);
                    width: 16px;
                    height: 16px;
                    background: rgba(255, 255, 255, 0.5);
                    border-radius: 2px;
                    border: 1px solid #9e9e9e;
                }

                svg {
                    position: absolute;
                    width: 16px;
                    height: 16px;
                    padding: 3px;
                    left: 0;
                    top: 50%;
                    box-sizing: border-box;
                    transform: translateY(-50%);
                    color: #fff;
                }

                &.active {
                    &::before {
                        // background: #ea4c89;
                        // border-color: transparent;
                    }

                    svg {
                        display: block;
                        color: #ea4c89;
                    }
                }
            }

            &>button {
                width: 108px;
                height: 36px;
                border-radius: 8px;
                transition: initial;
                margin-left: 16px;
                color: #fff !important;
            }
        }

        &[fixed='fixed'] {
            position: fixed;
            top: 0;
            left: 228px;
            width: calc(100vw - 228px);
            z-index: 99;
            background-color: transparent;
            pointer-events: none;
            box-sizing: border-box;
            padding: 0 168px;

            &>p {
                display: none;
            }

            fieldset {
                position: relative;
                height: 60px;
                display: flex;
                align-items: center;
                justify-content: flex-end;
                width: 100%;
                margin: 0 auto;
                max-width: 1080px;
                box-sizing: border-box;
                padding: 0 27px;
                z-index: 99;
                transition: margin 0.5s;
                margin-top: 0;
            }

            &+ul {
                padding-top: 16px;
            }
        }
    }

    &>ul {
        display: flex;
        flex-wrap: wrap;
        margin: 26px -6px 0;

        li {
            width: calc(20% - 12px);
            margin: 6px;
            border-radius: 4px;
            position: relative;
            box-shadow: 0 0 2px rgba(0, 0, 0, 0.2);
            overflow: hidden;

            figure {
                content: '';
                display: block;
                position: relative;
                padding-bottom: 100%;
                cursor: pointer;
            }

            img {
                position: absolute;
                width: 100%;
                height: 100%;
                left: 0;
                top: 0;
            }

            span {
                position: absolute;
                right: 7px;
                bottom: 7px;
                width: 30px;
                height: 30px;
                opacity: 0;
                transition: all 0.2s;
                color: #f6f6f6;
                cursor: pointer;

                svg {
                    width: 100%;
                    height: 100%;
                }

                &:hover {
                    color: #929292;
                }
            }

            &>i {
                position: absolute;
                left: 8px;
                top: 8px;
                color: #666;
                width: 16px;
                height: 16px;
                background: #fff;
                border-radius: 2px;
                border: 1px solid #9e9e9e;
                cursor: pointer;
                pointer-events: none;
                opacity: 0;
                transition: all 0.2s;

                svg {
                    position: absolute;
                    width: 16px;
                    height: 16px;
                    left: 50%;
                    top: 50%;
                    padding: 3px;
                    box-sizing: border-box;
                    transform: translate(-50%, -50%);
                    opacity: 0;
                }

                &:hover {
                    display: block;
                }
            }

            &:hover {
                box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.12);

                &>i {
                    opacity: 1;

                    svg {
                        color: #000;
                        opacity: 0.3;
                    }
                }

                &>span {
                    opacity: 1;
                    pointer-events: all;
                }
            }

            &.active {
                &>i {
                    &::before {
                        background: #ea4c89;
                        border-radius: 2px;
                        border-color: transparent;
                    }

                    svg {
                        opacity: 1;
                        color: #ea4c89;
                    }
                }
            }
        }
    }

    &.active {
        .detail-images-title fieldset {
            opacity: 1;
            pointer-events: all;
        }

        ul li i {
            opacity: 1;
        }
    }
}

.detail-downloading {
    &::v-deep .dialog-content {
        background: #ffffff;
        border-radius: 28px;

        .dialog-body {
            width: 320px;
            height: 320px;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            justify-content: center;
            align-items: center;
        }
    }

    .el-progress {
        width: 96px;
        height: 96px;

        &::v-deep {
            .el-progress-circle {
                width: 96px;
                height: 96px;
            }

            .el-progress__text {
                font-size: 20px;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                color: #000000;
            }
        }
    }

    p {
        margin-top: 24px;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        line-height: 16px;
    }
}
</style>
